package tables

import (
	"time"

	"mini-admin/internal/open"
	v1 "mini-admin/internal/open/service/v1"

	"mini-admin/internal/conf"

	// "github.com/Cluas/go-wechat/wechat"
	wechat "gitee.com/quantum-force/wxopen-api"
	"github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/modules/db"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/parameter"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
	"github.com/GoAdminGroup/go-admin/template/types/action"
)

// GetExternalWechatDraft return the model from external data source.
func GetExternalWechatDraft(ctx *context.Context) (externalTable table.Table) {

	externalTable = table.NewDefaultTable(table.DefaultConfig())

	info := externalTable.GetInfo()
	info.AddField("草稿ID", "id", db.Int).FieldSortable()
	info.AddField("版本号", "user_version", db.Varchar)
	info.AddField("描述", "user_desc", db.Varchar)
	info.AddField("创建时间", "create_time", db.Varchar)

	info.SetTable("wechat_draft").
		SetTitle("微信模版草稿库").
		SetDescription("微信小程序模版草稿库").
		SetGetDataFn(func(param parameter.Parameters) ([]map[string]interface{}, int) {
			res := make([]map[string]interface{}, 0)
			client := wechat.NewClient(nil)
			openClient := open.New(conf.Conf.OpenAddress)
			resp, err := openClient.ComponentAccessToken(ctx.Request.Context(), &v1.ComponentAccessTokenRequest{
				Platform: v1.Platform_PLATFORM_WECHAT,
				AppId:    conf.Conf.WechatAppID,
			})
			if err != nil {
				return nil, 0
			}

			draftList, _, err := client.WXA.GetTemplateDraftList(ctx.Request.Context(), resp.ComponentAccessToken)
			if err != nil {
				return nil, 0
			}
			for _, draft := range draftList.DraftList {
				res = append(res, map[string]interface{}{
					"id":           draft.DraftID,
					"user_version": draft.UserVersion,
					"user_desc":    draft.UserDesc,
					"create_time":  time.Unix(draft.CreateTime, 0).Format(time.RFC3339),
					"bo":           "快餐"})
			}

			return res, len(draftList.DraftList)
		})
	info.AddActionButtonFront("移动到模版库", action.Ajax("/admin/move_to_template",
		func(ctx *context.Context) (success bool, msg string, data interface{}) {
			draftID := ctx.FormValue("id")
			client := wechat.NewClient(nil)
			openClient := open.New(conf.Conf.OpenAddress)
			resp, err := openClient.ComponentAccessToken(ctx.Request.Context(), &v1.ComponentAccessTokenRequest{
				Platform: v1.Platform_PLATFORM_WECHAT,
				AppId:    conf.Conf.WechatAppID,
			})
			if err != nil {
				return false, err.Error(), ""
			}
			if _, err := client.WXA.AddToTemplate(ctx.Request.Context(), resp.ComponentAccessToken, &wechat.AddToTemplateRequest{DraftID: draftID}); err != nil {
				return false, err.Error(), ""
			}
			return true, "success", ""
		},
	))
	return
}
